<?php

namespace services\linkedcare;

use common\components\Service;
use common\helpers\CommonHelper;
use common\helpers\DateHelper;
use common\helpers\RedisHelper;
use common\models\linkedcare\LinkedcareChannel;
use common\models\linkedcare\LinkedcareTags;
use common\models\linkedcare\LinkedcareUser;
use common\models\linkedcare\LinkedcareAuth;
use common\models\log\LogReqPatient;
use common\models\patient\Patient;
use services\patient\PatientService;
use Yii;


class LinkedcareAuthService extends Service
{
    /**
     * 获取E看牙请求头
     * @return array|string[]
     */
    public static function getReqHeaderByEky(): array
    {
        $linkcareAuth = LinkedcareAuth::findOne(1);
        if (empty($linkcareAuth)) {
            return [];
        }
        // headers
        $headers = [
            "Accept: application/json, text/plain, */*",
            "Authorization: bearer {$linkcareAuth->access_token}",
            "Clientid: {$linkcareAuth->client_id}",
            "Origin: https://jgkqjt.linkedcare.cn",
            "Referer: https://jgkqjt.linkedcare.cn/",
            "Requestid: 856AE843-68FD-434B-9085-0EDCF4937253",
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
        ];
        return $headers;
    }

    /**
     * 获取新增患者请求数据
     * @return array
     */
    public static function getInitPostPatientData(): array
    {
        return [
            'extension' => [
                'onlineConsultantId' => 0,// 人员ID(网电咨询师ID)【kq_consult_id】
            ],
            "name" => "",// 姓名
            "sex" => 0,// 0未知
            "telephoneNumberList" => [
                [
                    'attributes' => 'mobile',
                    'displayOrder' => 1,
                    'mobileType' => '本人',
                    'mobile' => '',// 手机号
                    'patientId' => 0,
                ]
            ],
            'brithType' => null,
            'birth' => '',// 生日【当天日期】
            'age' => 0,// 年龄【0】
            'sourceTypeLevel1' => "网络部",// 一级渠道名
            'sourceType' => "新媒体1",// 二级渠道名
            'refereeName' => "飞鱼表单",// 三级渠道名
            'refereeMobileOrCode' => "fybd",// 三级渠道code
            'refereeId' => 0,
            'privateTag' => [// 归属人
                'tagStr' => null,
                'ownerId' => 3686,// 人员ID【kq_user_id】
            ],
            'patientTagUseList' => [// 患者标签【tag_id 种植：种1、种2、种3 正畸：正畸】
//                ['tagId' => 2170],
//                ['tagId' => 2171],
//                ['tagId' => 2172],
            ],
            'notes' => '',// 备注【remark_dict值 + 地区 + 创建时间】
            'patientFreeField' => [
                'field1' => null,
                'field2' => null,
                'field3' => null,
                'field4' => null,
                'field5' => null,
                'field6' => null,
                'field8' => null,
                'targetType' => 1,
            ],
            'mobile' => '',// 手机号
            'phoneNumber' => null,
            'patientType' => '临时',// 患者类型
            'privateId' => '',// 病历号【L001 + 0621 + 01（测试三位行不行）】
            'refereePatientId' => null,
        ];
    }

    /**
     * 获取新增患者请求数据
     * @return array
     */
    public static function getInitPostProjectData(int $patientId): array
    {
        return [
            'content' => "(1).病情主诉：\n(2).适合回访时间：\n(3).倾向专家：\n(4).其他：",
            'consultItems' => "",// 咨询项目 正畸=成人矫正 种植：种1、种2、种3
            'channel' => 1,
            'consultTime' => DateHelper::timestampToDate(time()),// 当前时间 2023-06-21 16:45:25
            'patientId' => $patientId,// 上一个接口返回ID
            'isFirstCreatePatient' => true,
        ];
    }

    /**
     * 获取患者表单请求数据
     * @param int $patientId
     * @return array
     */
    public static function getInitChannelData(int $patientId, array $params): array
    {
        return [
            'targetType' => 1,
            'targetId' => $patientId,
            'field1' => null,
            'field2' => null,
            'field3' => null,
            'field4' => null,// 意向植体
            'field5' => null,
            'field6' => null,
            'field7' => null,
            'field8' => null,
            'field9' => null,// 营销活动
            'field10' => $params['channel_name'] ?? null,// 渠道
            'field11' => $params['spoker_name'] ?? null,// 代言人
            'field12' => null,// 折扣比例
            'field13' => null,
        ];
    }

    /**
     * 获取新增回访请求数据
     * @return array
     */
    public static function getInitCallbackData(int $patientId, string $callbackName, int $planVisitorId, array $tagIds, string $notes): array
    {
        return [
            "visitorId" => null,
            "type" => "二次留咨：高意向",
            "content" => $notes,// 新增患者那个时候填的“患者备注”内容
            "method" => null,
            "satisfaction" => null,
            "dealIntention" => "",
            "dealPlanTime" => "",
            "dealPlanAmount" => "",
            "planVisitorId" => $planVisitorId,// 计划执行人ID
            "planVisitorName" => $callbackName,// 计划执行人姓名【按顺序分配到的人】
            "batchPlanTimes" => [
                DateHelper::timestampToDate(time()),// 默认当前时间
            ],
            "notes" => "",
            "state" => null,
            "transactions" => null,
            "phoneCallIds" => null,
            "patientTags" => [
                "patientId" => $patientId,
                "tagIds" => $tagIds
            ],
            "patientPrivateTag" => [
                "patientId" => $patientId,
                "ownerId" => 3686,// 从 https://api-hd02.linkedcare.cn:9001/api/v1/identity 获取
                "tagStr" => ""
            ],
            "patientId" => $patientId,
        ];
    }

    /**
     * 获取新增患者请求数据
     * @return array
     */
    public static function getInitSearchPatientData($searchString): array
    {
        return [
            'isBusyRequest' => false,
            'isExactMatchSelected' => false,
            'orderField' => '',
            'pageIndex' => '1',
            'pageSize' => '10',
            'searchString' => $searchString,// 手机号
        ];
    }

    /**
     * 提交请求，新增患者
     * @param string $date
     * @param int $channelId
     * @param Patient $patient
     * @param LinkedcareUser $user
     * @return LogReqPatient|null
     * @throws \Exception
     */
    public static function addPatient(string $date, Patient $patient): ?LogReqPatient
    {
        // 获取请求头
        $headers = self::getReqHeaderByEky();
        if (empty($headers)) {
            return null;
        }

        // 新增患者post数据
        $data = self::getInitPostPatientData();
        $data['name'] = $patient->name;
        $data['gender'] = 0;
        $data['telephoneNumberList'][0]['mobile'] = $patient->mobile;
        $data['birth'] = $date;
        $data['age'] = 0;
        // 标签
        $data['patientTagUseList'] = LinkedcareTagsService::getAddPatientTags();
        // 备注【remark_dict值 + 地区 + 创建时间】
        $discountRate = PatientService::getDiscountRate($patient->discount_rate);
        $data['notes'] .= $patient->remark ? $patient->remark . "\n" . $discountRate : $discountRate;
        $data['mobile'] = $patient->mobile;
        $data['privateId'] = $patient->private_id;
        // 归属人
        $data['extension']['onlineConsultantId'] = LinkedcareUserService::getAddPatientUser()->kq_consult_id ?? '';
        // 渠道
        $channelList = LinkedcareChannelService::getChannelTreeList(RedisHelper::getPatientType($patient->type_id)->channel_id ?? 0);
        $data['sourceTypeLevel1'] = $channelList[0]->source_name ?? '';
        $data['sourceType'] = $channelList[1]->source_name ?? '';
        $data['refereeName'] = $channelList[2]->source_name ?? '';
        $data['refereeMobileOrCode'] = $channelList[2]->source_name_code ?? '';
        // 1.新增患者
        $ekyUrl = Yii::$app->params['eky_url'];
        $res = CommonHelper::https_request("{$ekyUrl}/api/v1/patient", $data, $headers);
//        var_dump($res);
        $resData = json_decode($res, true);
        $resData['id'] = $resData['id'] ?? 0;
//        var_dump($resData);
//        echo PHP_EOL."===========".PHP_EOL;
        // 2.设置咨询项目
        $projectData = $res1Data = [];
        $channelData = $res2Data = [];
        if ($resData['id']) {
            $projectData = self::getInitPostProjectData($resData['id']);
            // {"id":541288,"channel":0,"apptStartTime":null,"apptEndTime":null,"isFirstVisit":false,"apptOfficeId":0,"state":0,"consultItems":null,"content":"(1).病情主诉：\n(2).适合回访时间：\n(3).倾向专家：\n(4).其他：","method":null,"notes":null,"orderDateTime":"0001-01-01T00:00:00","recordCreatedTime":"2023-06-26T09:15:32.6796594+08:00","recordCreatedUser":3686,"recordCreatedUserName":null,"createdUserDepartment":null,"patientId":1311016,"consultTime":"2023-06-26T09:15:34","reason":null,"intention":null,"intentionDesc":null,"officeId":36,"privateTag":null,"appointmentId":null,"chiefComplaint":null,"appointmentDoctorId":null,"appointmentDoctorName":null,"onlineConsultFreefieldDtos":null}
            $res1 = CommonHelper::https_request("{$ekyUrl}/api/v1/online-consult", $projectData, $headers);
            $res1Data = json_decode($res1, true);
//            $res1Data['id'] = $resData['id'] ?? 0;
//            var_dump($res1Data);
//            echo PHP_EOL."===========".PHP_EOL;
            // 设置渠道
            $channelData = self::getInitChannelData($resData['id'], [
                'spoker_name' => Yii::$app->user->identity->user->spoker->name
            ]);
            $res2 = CommonHelper::https_request("{$ekyUrl}/api/v1/free-field/save", $channelData, $headers);
            $res2Data = json_decode($res2, true);
//            var_dump($res2Data);
//            echo PHP_EOL."===========".PHP_EOL;
        }

        // 保存请求记录
        $logReqPatient = new LogReqPatient();
        $logReqPatient->patient_id = $patient->id;
        $logReqPatient->add_user_req = $data;
        $logReqPatient->add_user_resp = $resData ?: [];
        $logReqPatient->add_project_req = $projectData;
        $logReqPatient->add_project_resp = $res1Data ?: [];
        $logReqPatient->add_channel_req = $channelData;
        $logReqPatient->add_channel_resp = $res2Data ?: [];
        $logReqPatient->saveAndCheckResult();
//        if (!isset($resData['id']) || empty($resData['id'])) {// 未新增成功，抛出异常
//            throw new \Exception($res);
//        }
        return $logReqPatient;
    }

    /**
     * 提交请求，新增回访人【患者存在情况】
     * @param int $ePatientId
     * @param Patient $patient
     * @param LinkedcareUser $user
     * @return LogReqPatient|null
     * @throws \Exception
     */
//    public static function addCallback(int $ePatientId, Patient $patient, LinkedcareUser $user): ?LogReqPatient
//    {
//        // 获取请求头
//        $headers = KqLinkcareAuthService::getReqHeaderByEky();
//        if (empty($headers)) {
//            return null;
//        }
////        echo "回访======================".PHP_EOL;
//        // 登陆账号信息
//        $ekyUrl = Yii::$app->params['eky_url'];
////        $res = CommonHelper::https_request("{$ekyUrl}/api/v1/identity", null, $headers);
////        $identityData = json_decode($res, true);
////        print_r($identityData);
//        // 患者信息
//        $queryData = ['patientId' => $ePatientId];
//        $res1 = CommonHelper::https_request("{$ekyUrl}/api/v1/patient/head-info", $queryData, $headers);
//        $patientData = json_decode($res1, true);
////        print_r($patientData);
//        // 获取标签IDs
//        $tagName = array_column($patientData['tags'] ?? [], 'itemName');
//        $tagIds = LinkedcareTagsService::getTagIdsByName(array_merge($tagName, ['二次留咨']));
//
//        // 回访
//        $remarkDictValus = implode(' | ', array_values($patient->source_data['remark_dict'] ?? []));
//        $callbackData = self::getInitCallbackData($ePatientId, $user->name, $user->kq_consult_id, $tagIds, $remarkDictValus ?: $patientData['notes']);
//        $res = CommonHelper::https_request("{$ekyUrl}/api/v3/revisit/batch-plantime-create", $callbackData, $headers);
//        $resData = json_decode($res, true);
////        echo "回访======================".PHP_EOL;
////        var_dump($res);
////        var_dump($resData);
//        // 保存请求记录
//        $logReqPatient = new LogReqPatient();
//        $logReqPatient->patient_id = $patient->id;
//        $logReqPatient->add_user_req = $callbackData;
//        $logReqPatient->add_user_resp = $resData ?: [];
//        $logReqPatient->add_project_req = [];
//        $logReqPatient->add_project_resp = [];
//        $logReqPatient->add_channel_req = [];
//        $logReqPatient->add_channel_resp = [];
//        $logReqPatient->saveAndCheckResult();
//
//        return $logReqPatient;
//    }

    /**
     * 检查手机号在E看牙是否存在
     * @param string $mobile
     * @return array
     */
    public static function checkPhoneRepeatByEky(string $mobile, int $isSleep = 1): array
    {
        $res = [
            'id' => 0,
            'private_id' => '',// 病历号
            'is_repeat' => false,
        ];
        if (PatientService::hasRepeatMobie($mobile)) {
            $res['is_repeat'] = true;
            return $res;
        }

        // 获取请求头
        $headers = self::getReqHeaderByEky();
        if (empty($headers)) {
            return $res;
        }
        // 接口延迟请求
//        if ($isSleep) {
//            sleep(mt_rand(3, 10));
//        }
        // 1.查看患者手机号是否存在
        $queryData = self::getInitSearchPatientData($mobile);
        $query = http_build_query($queryData);
        $ekyUrl = Yii::$app->params['eky_url'];
        $res = CommonHelper::https_request("{$ekyUrl}/api/v1/patients?{$query}", null, $headers);
//        var_dump("{$ekyUrl}/api/v1/patients?{$query}");
//        var_dump($res);
        $resData = json_decode($res, true);
//        print_r($resData);exit();
//        return count($resData['items'] ?? []) > 0 ? true : false;
        return [
            'id' => $resData['items'][0]['id'] ?? 0,
            'private_id' => $resData['items'][0]['privateId'] ?? '',// 病历号
            'is_repeat' => count($resData['items'] ?? []) > 0 ? true : false,
        ];
    }
}
